//日期
function formatDate(str) { // data数据, date时间
    var theDate = new Date(str);
    // 按照我们想要的格式, 年-月-日 时:分:秒
    var year = theDate.getFullYear();
    var month = theDate.getMonth() + 1;
    var day = theDate.getDate();
    // var hours = theDate.getHours();
    // var minutes = theDate.getMinutes();
    // var seconds = theDate.getSeconds();

    var fn = val => val < 10 ? '0' + val : val;
    return [year, month, day].map(fn).join("-");
}


function getlist() {

    $.ajax({
        type: 'GET',
        url: 'http://localhost:8888/admin/comments',
        beforeSend: function (xhr) {
            xhr.setRequestHeader("Authorization", "Bearer eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJ1c2VybmFtZSI6ImFkbWluIiwiaWQiOjEsImlhdCI6MTYwODE3MDE3NSwiZXhwIjoxNjA4NjAyMTc1fQ.dTdbGwUoTl_NDBNK1KRnyfCtSy5ShDg4pBpl27Yre04");
        },
        success: function (res) {

            $('.layui-table tbody').empty();
            console.log(res);
            res.data.forEach(function (obj, index) {
                var { id, uname, content, cdate } = obj;
                var str = `
                    <tr>
                        <td>${id}</td>
                        <td>${uname}</td>
                        <td>${content}</td>
                        <td>${formatDate(cdate)}</td>
                        <td>
                            <button myid=${id} class="del layui-btn layui-btn-normal layui-btn-xs ">删除</button>
                        </td>
                    </tr>  `
                $('.layui-table tbody').append(str);

            })
        }
    })
}
getlist()
//  事件委托  删除评论
$('.layui-table tbody').on('click', '.del', function () {
    var res = $(this).attr('myid')
    layer.confirm('确定删除么?', function (index) {
        $.ajax({
            type: 'delete',
            url: 'http://localhost:8888/admin/comments/' + res,
            beforeSend: function (xhr) {
                xhr.setRequestHeader("Authorization", "Bearer eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJ1c2VybmFtZSI6ImFkbWluIiwiaWQiOjEsImlhdCI6MTYwODE3MDE3NSwiZXhwIjoxNjA4NjAyMTc1fQ.dTdbGwUoTl_NDBNK1KRnyfCtSy5ShDg4pBpl27Yre04");
            },
            data: {
                "status": 0,
                "message": "删除评论成功"
            },
            success: (res) => {
                console.log(res)

                getlist()
            }
        })
        layer.close(index);
    });



})
